package com.woniuxy.shop.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.woniuxy.shop.entity.Address;
import com.woniuxy.shop.entity.ResponseEntity;
import com.woniuxy.shop.entity.User;
import com.woniuxy.shop.service.AddressService;
import com.woniuxy.shop.service.TopAddressService;
import com.woniuxy.shop.service.UserService;

public class ShopUtils {
	static TopAddressService tas = new TopAddressService();
	static UserService us = new UserService();
	/**
	 * 判断字符串是否为空
	 * @param s
	 * @return
	 */
	public static boolean isEmpty(String s) {
		return s==null||s.trim().equals("");
	}
	
	/**
	 * 返回指定格式的当前时间字符串
	 * @return
	 */
	public static String getNowTimeWithType() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
		return sdf.format(new Date());
	}
	
	public static String getNowTimeNoSymbol() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyMMddHHmmss");
		return sdf.format(new Date());
	}
	
	/**
	 * 获取用户登录IP
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
	    String ip = request.getHeader("X-Forwarded-For");
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getHeader("HTTP_CLIENT_IP");
	    }
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	    }
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getRemoteAddr();
	    }
	      return ip;
	}
	
	public static void write( HttpServletResponse resp,ResponseEntity rese) throws IOException {
		PrintWriter writer  = resp.getWriter();
		writer.write(JSON.toJSONString(rese));
		writer.close();
	}
	
	public static void responseTo(String name,String value,String location,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute(name, value);
		request.getRequestDispatcher(location).forward(request, response);
	}

	public static void sendMail(String mail) {
		try {
			final Properties props = new Properties();
			props.put("mail.user", mail);
			props.put("mail.password", "toobpqqhssfkihei"); // 授权码
			props.put("mail.smtp.auth", "true");
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", "smtp.qq.com");
			props.put("mail.smtp.port", "25");

			Session mailSession = Session.getDefaultInstance(props);

			Message msg = new MimeMessage(mailSession);
			msg.setFrom(new InternetAddress(mail));  //发件人
			msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(mail)); //收件人
			msg.setSubject("用户注册激活邮件-蜗牛学院"); //主题
			msg.setContent("<h1>此邮件为蜗牛学院电商平台激活邮件！请点击下面链接完成激活操作！</h1><br />" + "此邮件30分钟有效!"
					+ "<h4><a href='http://localhost:8080/woniushop/user?opr=active&email=" + mail
					+ "'>http://localhost:8080/woniushop/user?opr=active&email=" + mail
					+ "</a></h4>", "text/html;charset=UTF-8");
			msg.saveChanges();

			Transport transport = mailSession.getTransport("smtp");
			transport.connect(props.getProperty("mail.smtp.host"), props.getProperty("mail.user"),
					props.getProperty("mail.password"));
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取指定用户id的地址，包括详细地址
	 * @param id 用户id
	 * @return
	 */

	public static List<Address> getAddresses(int id){
		AddressService as = new AddressService();
		List<Address> addresses = as.getAddressByUserId(id);
		if(addresses!=null) {
			for (Address address : addresses) {
				setTopName(address);
			}
		}
		return 	addresses;	
	}
	
	/**
	 * 为地址设置top名
	 * @param address
	 */
	public static void setTopName(Address address) {
		List<String> names = tas.getAllTop(address.getTopaddress());
		if(names.size()==2) {
			address.setProvience(names.get(0));
		}else {
			address.setArea(names.get(0));
			address.setCity(names.get(1));
			address.setProvience(names.get(2));
		}
	}
	
	/**
	 * 
	 * @param n n=1表示校验账号，否则表示校验邮箱
	 * @param value 邮箱或账号
	 * @return
	 */
	public static boolean checkActOrEmail(int n,String value) {
		User u;
		if(n==1) {
			u  = us.getUserByAct(value);
		}else {
			u = us.getUserByEmail(value);
		}
		return u==null?true:false;
	}
	
	/**
	 * 校验一个字符串是否是字母数字下划线汉字组成
	 * @param act 账号
	 * @return
	 */
	public static boolean checkAct(String act) {
		Pattern pt = Pattern.compile("[\u4e00-\u9fa5\\w]+");
		Matcher mt = pt.matcher(act);
		return mt.matches();
	}
	
	/**
	 * 校验是不是正确的手机号码
	 * @param phone
	 * @return
	 */
	public static boolean checkPhone(String phone) {
		Pattern pt = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
		Matcher mt = pt.matcher(phone);
		return mt.matches();
	}
	
	/**
	 * 校验是不是正确的邮箱
	 * @param mail
	 * @return
	 */
	public static boolean checkMail(String mail) {
		//其中\w代表可用作标识符的字符,不包括$. \w+表示多个
        //  \\.\\w表示点.后面有\w 括号{2,3}代表这个\w有2至3个
        //牵扯到有些邮箱类似com.cn结尾 所以(\\.\\w{2,3})*后面表示可能有另一个2至3位的域名结尾
        //*表示重复0次或更多次
		Pattern pt = Pattern.compile("\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}");
		Matcher mt = pt.matcher(mail);
		return mt.matches();
	}
	
}
